#1封装 三级商品分类
from collections import OrderedDict

from apps.goods.models import GoodsChannel





def get_categories():

    # 1.1 获取所有频道表 37个数据
    channels = GoodsChannel.objects.order_by('group_id','sequence')

    categories = OrderedDict()
    for channel in channels:
        # 1.2根据频道 获取 组 id
        group_id = channel.group_id
        # 1.3判断 如果 字典里面 有组id 不再生成新的字典
        if group_id not in categories:
            categories[group_id] = {'channels': [], "sub_cats": []}

        # 1.4根据频道 获取 一级分类 category 外键属性
        # 一级分类 需要 多加一个key -url频道列表
        cat1 = channel.category
        # 动态添加属性
        cat1.url = channel.url
        categories[group_id]['channels'].append(cat1)

        # 1.5 处理二级 三级 分类 cat1.subs.all() cat2.subs.all()
        for cat2 in cat1.subs.all():
            cat2.subs_cats = []
            for cat3 in cat2.subs.all():
                cat2.subs_cats.append(cat3)

            categories[group_id]['sub_cats'].append(cat2)

    return categories